package net

import (
	"gitee.com/dennis-kk/service-box-go/util/slog"
	"github.com/panjf2000/gnet"
)

// gnetConnector wrapper for network connector
// gnet client maybe not corss platform
type gnetConnector struct {
	client *gnet.Client
}

//newBoxConnector create connector by loop
func makeConnector(v interface{}) IBoxConnector {
	if gnetEH, ok := v.(*clientEH); ok {
		bc := &gnetConnector{}
		var err error
		if bc.client, err = gnet.NewClient(gnetEH); err != nil {
			slog.Error("[BoxNetwork] create sbox connector error %v !", err)
			return nil
		}
		return bc
	}
	return nil
}

func (bc *gnetConnector) Start() error {
	if bc == nil || bc.client == nil {
		panic("[BoxNetwork] box network is invalid !")
	}

	return bc.client.Start()
}

// ConnectTo connect to remote server, this function will block current goroutine
func (bc *gnetConnector) ConnectTo(network, address string) (boxConn IBoxConn, err error) {
	if bc == nil || bc.client == nil {
		panic("[BoxNetwork] box network is invalid !")
	}

	// Dial function will not trigger OnOpened
	conn, err := bc.client.Dial(network, address)
	if err == nil {
		//TODO manager connection
		slog.Info("[BoxNetwork] connect to remote %s:%s successfully!", network, address)
		boxConn = &gnetConn{
			conn:  conn,
			state: BoxConnConnecting,
		}
	}
	return
}

func (bc *gnetConnector) Stop() error {
	if bc == nil || bc.client == nil {
		return nil
	}
	return bc.client.Stop()
}
